package com.eusoft.demo.controller;


import com.eusoft.demo.entity.Result;
import com.eusoft.demo.entity.User;
import com.eusoft.demo.service.UserService;
import com.eusoft.demo.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author eusoft
 * @since 2021-10-12
 */
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/user/login")
    //@CrossOrigin
    public Result login(User user) {
        try {
            User userDB = userService.login(user);
            Map<String, String> map = new HashMap<>();//用来存放payload
            map.put("aid",userDB.getAid().toString());
            Map<String,String> token = new HashMap<>();
            token.put("token",JWTUtils.getToken(map));
            return ResultUtils.success(token,"登录成功！");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return ResultUtils.error(e.getMessage());
        }
    }

    /**
     *
     * @param request
     * @return
     */

    @GetMapping("/manage/list")
    //@CrossOrigin(origins = "*",allowedHeaders = "*")
    public Result getList(HttpServletRequest request){
        try{
            String token = request.getHeader("token");
            Integer aid = GetAidUtil.getByToken(token);
            List<User> users = userService.getOtherUserList(aid);
            return ResultUtils.success(users,"数据获取成功");
        }
        catch (Exception e){
            return ResultUtils.error(e.getMessage());
        }

    }

    @GetMapping("/getCurrentUser")
    //@CrossOrigin(origins = "*",allowedHeaders = "*")
    public Result getCurrentUser(HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        try{
            String token = request.getHeader("token");
            if(token.equals("null")){
                return ResultUtils.newData(map,"用户信息为空，请重新登录",401,false);
            }
            Integer aid = GetAidUtil.getByToken(token);
            User user = userService.getUserByAid(aid);
            map.put("status",true);
            map.put("userid",user.getAid().toString());
            map.put("name",user.getName());
            map.put("avatar","https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png");
            return ResultUtils.newData(map,"用户信息获取成功",200,true);
        }
        catch (Exception e){
            return ResultUtils.newData(map,e.getMessage(),503,false);

        }
    }

}
